<?php
/**
 *
 * @package Aurora Project
 * @version $Id: unix_line_endings.php 3 2009-07-31 02:25:51Z sTraTosphere.programming $
 * @copyright 2008 Aurora PHP Group
 * @author Deadpool (http://the-webmasters-resource.info)
 * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
 * 
 * @note: This file is independent of the Aurora core, so use wherever :)
 */

// Borrowed from the Aurora CMS Project

@set_time_limit(0);
error_reporting(E_ALL);

// Output to text/html
header('Content-type: text/html; charset=UTF-8');

unix_line_endings::parse('..');

/**
 */
class unix_line_endings
{
	private static $fix = "\r"; #._**
	private static $file_contents;
	private static $version = '0.0.3';

	// __constructor
	public static function parse($dir)
	{
		if (!file_exists($dir) || !is_dir($dir))
		{
			die("$dir does not exist.");
		}

		$file_ary = self::recursive_scandir($dir);

		foreach ($file_ary as $item)
		{
			self::fix_bad_file($item);
		}
	}

	// Recurive Scan-dir function 
	private static function recursive_scandir($root_dir, $passed_ary = array())
	{
		$data_ary = $passed_ary;
		foreach(scandir($root_dir) as $key => $_val)
		{
			// No images @)(!*@*!!~~~~
			if (in_array(substr(strrchr($_val, '.'), 1), array('xcf'/* Yeah, I use GIMP, what about it? */, 'zip', 'svn', 'gif', 'png', 'tif', 'jpg', 'jpeg')))
			{
				continue;
			}

			$item = $root_dir . '/' . $_val;
			if (is_file($item) && is_readable($item) && $_val != basename(__FILE__))
			{
				$data_ary[] = $item;   
			}
			else if (is_dir($item) && is_readable($item))
			{
				if (!in_array($_val, array('..', '.', './', '../')))
				{
					$data_ary = self::recursive_scandir($item, $data_ary);
				}
			}
		}

		return $data_ary;
	}

	// Fix a file to have correct UNIX line endings
	public static function fix_bad_file($file)
	{
		self::$file_contents = file_get_contents($file);

		if (self::has_unix_endings(self::$file_contents))
		{
			echo "<b>$file</b> <em>has UNIX endings.</em><br /><br />";
		}
		else
		{
			self::fix_unix_endings(self::$file_contents);

			@file_put_contents($file, self::$file_contents);

			echo "<b>$file</b> <em>has been fixed to have UNIX line endings</em> :)<br /><br />";
		}
	}

	// Check content for UNIX line endings
	private static function has_unix_endings($dir_contents)
	{
		if (strpos($dir_contents, self::$fix) !== false)
		{
			return false;
		}

		return true;
	}

	// Fix UNIX line endings 
	private static function fix_unix_endings(&$dir_contents)
	{
		$dir_contents = str_replace(self::$fix, '', $dir_contents);
	}
}
?>